package com.zhiyizhen.callnumber.component;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.speech.tts.Voice;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhiyizhen.callnumber.R;
import com.zhiyizhen.callnumber.common.AppUtil;
import com.zhiyizhen.callnumber.common.DataCache;
import com.zhiyizhen.callnumber.common.DateUtil;
import com.zhiyizhen.callnumber.common.ImageLoader;
import com.zhiyizhen.callnumber.common.LogUtil;
import com.zhiyizhen.callnumber.common.RxJavaUtil;
import com.zhiyizhen.callnumber.common.ToastUtil;
import com.zhiyizhen.callnumber.common.view.BaseActivity;
import com.zhiyizhen.callnumber.common.view.CommonDialog;
import com.zhiyizhen.callnumber.component.api.IApiService;
import com.zhiyizhen.callnumber.component.bean.BoardListItem;
import com.zhiyizhen.callnumber.component.bean.LoginBean;
import com.zhiyizhen.callnumber.databinding.ActivityMainBinding;
import com.zhiyizhen.callnumber.net.ServiceFactory;
import com.zhiyizhen.callnumber.net.response.ResponseData;
import com.zhiyizhen.callnumber.net.response.ResponseObserver;
import com.zhiyizhen.callnumber.websocket.WebSocketManager;
import com.zhiyizhen.callnumber.websocket.WebSocketService;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/**
 * description
 *
 * @author dahu \n
 */
public class MainActivity extends BaseActivity implements TextToSpeech.OnInitListener {
    private ActivityMainBinding binding;
    protected RecyclerView mRecyclerView;
    private BoardListAdapter adapter;
    private LoginBean loginBean;
    private TextToSpeech tts;
    private final List<BoardListItem> resultList = new ArrayList<>();
    private Handler handler;
    private Runnable loopRunnable;
    private int totalPageCount = 0;
    private int currentPageCount = 0;

    private WebSocketManager webSocketManager;
    private WebSocketService webSocketService;
    private boolean isServiceBound = false;

    private final static int DELAY = 30000;

    private long callTime;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // 服务绑定成功时调用
            WebSocketService.LocalBinder binder = (WebSocketService.LocalBinder) service;
            webSocketService = binder.getService();
            isServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // 服务意外断开时调用
            isServiceBound = false;
        }
    };

    // 广播接收器
    private final BroadcastReceiver webSocketReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;

            // 处理消息广播
            if (action.equals(WebSocketService.ACTION_WEBSOCKET_MESSAGE)) {
                String message = intent.getStringExtra(WebSocketService.EXTRA_MESSAGE);
                LogUtil.d("message:" + message);
                appendMessage(message);

                handler.removeCallbacks(loopRunnable);
                getBoardList();
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mRecyclerView = binding.recyclerView;
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        adapter = new BoardListAdapter(this);
        mRecyclerView.setAdapter(adapter);

        tts = new TextToSpeech(this, this);

        handler = new Handler(Looper.getMainLooper());
        loopRunnable = new Runnable() {
            @Override
            public void run() {
                binding.timeTv.setText(DateUtil.getCurrentTime());
                if (System.currentTimeMillis() - callTime > 3 * 60 * 1000) {
                    binding.callingTv.setVisibility(View.INVISIBLE);
                    binding.messageTv.setVisibility(View.INVISIBLE);
                }
                adapter.clear();
                currentPageCount++;
                LogUtil.d("currentPageCount == " + currentPageCount);
//                if (currentPageCount < totalPageCount) {
//                    adapter.addAll(resultList.subList(6 * currentPageCount, 6 * (currentPageCount + 1)));
//                    LogUtil.d("currentPageCount == aaa");
//                } else {
//                    adapter.addAll(resultList.subList(6 * currentPageCount, resultList.size() - 1));
//                    LogUtil.d("currentPageCount == bbb");
//                }

                adapter.addAll(resultList.subList((currentPageCount - 1) * 6, Math.min(currentPageCount * 6, resultList.size())));
                LogUtil.d("currentPageCount == adapter" + adapter.getItemCount());

                if (currentPageCount == totalPageCount) {
                    mRecyclerView.postDelayed(() -> {
                        getBoardList();
                        handler.removeCallbacks(loopRunnable);
                    }, DELAY);
                } else {
                    handler.postDelayed(this, DELAY);
                }
                binding.pageTv.setText(currentPageCount + "/" + totalPageCount);
            }
        };

        // 启动并绑定服务
        Intent intent = new Intent(this, WebSocketService.class);
        startService(intent); // 先启动服务
        bindService(intent, serviceConnection, BIND_AUTO_CREATE); // 再绑定服务

        initSocket();
        registerBroadcastReceiver();
        back();
    }

    private void back() {
        // 注册返回事件回调
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                showLogoutDialog();
            }
        });
    }

    private CommonDialog dialog;
    public void showLogoutDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, (ViewGroup) this.getWindow().getDecorView(), false);

        CommonDialog.Builder builder = new CommonDialog.Builder(this);
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_btn).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.ok_btn).setOnClickListener(v -> {
            dialog.dismiss();
            relogin();
        });
    }

    public void relogin() {
        DataCache.setLoginBean(null);
        Intent intent = new Intent(AppUtil.getContext(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        AppUtil.getContext().startActivity(intent);
        finish();
    }

    private void initSocket() {
        // 初始化WebSocket管理器
        webSocketManager = WebSocketManager.getInstance();
    }

    private void stopWebSocketService() {
        if (isServiceBound && webSocketService != null) {
            webSocketService.stopServiceSafely();

            // 解绑服务
            unbindService(serviceConnection);
            isServiceBound = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loginBean = DataCache.getLoginBean();
        if (loginBean == null) {
            return;
        }
        ImageLoader.load(this, loginBean.getLogo(), binding.logoImg);
        binding.dateTv.setText(DateUtil.getCurrentWeekday() + " " + DateUtil.getCurrentDate());
        binding.timeTv.setText(DateUtil.getCurrentTime());
        binding.clinicNameTv.setText(loginBean.getClinicName());
        getBoardList();
        updateConnectionStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放 TTS 资源
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        if (handler != null && loopRunnable != null) {
            handler.removeCallbacks(loopRunnable);
        }
        stopWebSocketService();
        if (isServiceBound) {
            unbindService(serviceConnection);
            isServiceBound = false;
        }
        // 注销广播接收器
        unregisterReceiver(webSocketReceiver);
    }

    // 更新连接状态
    private void updateConnectionStatus() {
        if (webSocketManager.isConnected()) {
            LogUtil.d("连接状态: 已连接");
        } else {
            LogUtil.d("连接状态: 未连接");
        }
    }

    // 添加消息到界面
    private void appendMessage(String message) {
        if (TextUtils.isEmpty(message)) {
            binding.callingTv.setVisibility(View.INVISIBLE);
            return;
        }
        binding.callingTv.setVisibility(View.VISIBLE);
        binding.messageTv.setVisibility(View.VISIBLE);
        binding.messageTv.setText(message);
        binding.messageTv.requestFocus();
        speakText(message);
        callTime = System.currentTimeMillis();
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void registerBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WebSocketService.ACTION_WEBSOCKET_MESSAGE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(webSocketReceiver, filter, RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(webSocketReceiver, filter);
        }
    }

    private void getBoardList() {
        ServiceFactory.getService(IApiService.class)
                .getBoardList(loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {

                    @Override
                    protected void onSuccess(ResponseData<List<BoardListItem>> responseData) {
                        if (responseData == null || responseData.getData() == null) {
                            return;
                        }
                        List<BoardListItem> list = responseData.getData();
                        if (list == null || list.isEmpty()) {
                            return;
                        }
                        resultList.clear();
                        resultList.addAll(list);
                        currentPageCount = 0;
                        totalPageCount = (resultList.size() + 6 - 1) / 6;
                        showList();
                    }

                    @Override
                    protected void onFinally() {
                        super.onFinally();
//                        resultList.clear();
//                        for (int i = 0; i < 20; i++) {
//                            resultList.add(new BoardListItem("test" + i));
//                        }
//                        currentPageCount = -1;
//                        totalPageCount = (resultList.size() + 6 - 1) / 6;
//                        showList();
                    }
                });
    }

    private void showList() {
        handler.post(loopRunnable);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            // 设置语言（优先使用系统默认语言）
            Locale defaultLocale = Locale.CHINA;
            tts.setLanguage(defaultLocale);
            // 可选：设置语速（0.5f-2.0f，1.0f 为正常速度）
            tts.setSpeechRate(0.8f);
            // 可选：设置音调（0.5f-2.0f，1.0f 为正常音调）
            tts.setPitch(1.0f);

            // 设置语音类型
            Set<Voice> voices = tts.getVoices();
            for (Voice voice : voices) {
                // 筛选中文语音
                if (voice.getLocale().equals(Locale.CHINA)
                        || voice.getLocale().equals(Locale.CHINESE)) {

                    // 根据语音名称或属性判断是否为男声
                    // 不同引擎的语音名称格式可能不同，需要适配
                    String voiceName = voice.getName();
                    LogUtil.d("voiceName == " + voiceName);
                    if (voiceName.contains("cmn-cn-x-ccc-local")) {
                        tts.setVoice(voice);
                        return;
                    }
                }
            }
        }
    }

    private void speakText(String content) {
        if (content.isEmpty()) {
            ToastUtil.showShort("请输入要朗读的文本");
            return;
        }
        // 检查 TTS 引擎是否准备就绪
        if (tts.isSpeaking()) {
            tts.stop();
        }
        // 开始朗读
        // API 21 以上推荐使用 speak(CharSequence text, int queueMode, Bundle params, String utteranceId)
        tts.speak(content, TextToSpeech.QUEUE_FLUSH, null, "utteranceId");
    }

}
